<template>
  <div class="app-container">
    <div class="page-card">
      <div class="page-form">
        <el-select
          v-model="queryParams.deptId"
          placeholder="选择学校"
          clearable
          filterable
          @change="
            queryParams.classNames = '';
            handleSearch();
          "
          v-hasRole="['admin']"
        >
          <el-option
            v-for="dict in deptList"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId.toString()"
          />
        </el-select>
        <el-select
          v-model="queryParams.gradeName"
          placeholder="年级"
          clearable
          @change="
            queryParams.classId = '';
            handleSearch();
          "
        >
          <el-option
            v-for="dict in dict.type.grade"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-select
          v-model="queryParams.classNames"
          placeholder="班级"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in queryParamsBjlb"
            :key="dict.id"
            :label="dict.className"
            :value="dict.className"
          />
        </el-select>
        <el-select
          v-model="queryParams.roleId"
          placeholder="角色类型"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in roleList"
            :key="dict.roleId"
            :label="dict.roleName"
            :value="dict.roleId"
          />
        </el-select>
        <el-select
          v-model="queryParams.subject"
          placeholder="授课科目"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in xklb"
            :key="dict.subjectId"
            :label="dict.subjectName"
            :value="dict.subjectName"
          />
        </el-select>
        <el-input
          v-model="queryParams.nickName"
          placeholder="教师姓名"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.userId"
          placeholder="教师ID"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.userName"
          placeholder="手机号码&账号"
          clearable
          @input="handleSearch"
        />
      </div>
      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="userId"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          label="ID"
          align="center"
          prop="userId"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="姓名"
          align="center"
          prop="nickName"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="手机号&账号"
          align="center"
          prop="userName"
          :show-overflow-tooltip="true"
          width="180"
        />
        <el-table-column
          label="所属学校"
          align="center"
          prop="deptName"
          :show-overflow-tooltip="true"
          width="180"
        />
        <el-table-column
          label="角色"
          align="center"
          :show-overflow-tooltip="true"
          width="180"
        >
          <template slot-scope="scope">
            <span v-for="(v, i) in scope.row.userRoleVoList" :key="v.roleId"
              >{{ v.roleName }}
              <span v-if="i != scope.row.userRoleVoList.length - 1"
                >，</span
              ></span
            >
          </template>
        </el-table-column>
        <el-table-column label="授课科目" align="center" width="300">
          <template slot-scope="scope">
            <km-tag :option="scope.row.subject"></km-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="授课学段"
          align="center"
          :show-overflow-tooltip="true"
          width="140"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.school_segment_type"
              :value="scope.row.stage"
            />
          </template>
        </el-table-column>
        <el-table-column label="授课年级" align="center" width="160">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.grade"
              :value="scope.row.gradeName"
              :show-value="false"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="授课班级"
          align="center"
          prop="classNames"
          width="140"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding"
          width="160"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
            <el-link type="primary" @click="czmm(scope.row)">重置密码</el-link>
            <el-link type="danger" @click="del(scope.row.userId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-bottom">
      <div class="sel-box">
        <p>
          已选 <span>{{ ids.length }}</span> 项 / 共 {{ total }} 项
        </p>
        <el-button type="primary" @click="edit(false)">新增教师</el-button>
        <el-button type="primary" @click="upload.open = true"
          >批量导入</el-button
        >
        <el-button type="danger" :disabled="multiple" @click="del(false)"
          >批量删除</el-button
        >
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑教师"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="教师姓名" prop="nickName">
          <el-input v-model="editForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号&账号" prop="userName">
          <el-input v-model="editForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editForm.userId">
          <el-input
            v-model="editForm.password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属学校" prop="deptId" v-hasRole="['admin']">
          <el-select v-model="editForm.deptId">
            <el-option
              v-for="dict in deptList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="editForm.roleIds" multiple>
            <el-option
              v-for="dict in roleList"
              :key="dict.roleId"
              :label="dict.roleName"
              :value="dict.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授课科目" prop="subject">
          <el-select v-model="editForm.subject" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.subjectId"
              :label="dict.subjectName"
              :value="dict.subjectName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授课学段" prop="stage">
          <el-select v-model="editForm.stage" multiple @change="stageChange">
            <el-option
              v-for="dict in dict.type.school_segment_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授课年级" prop="gradeName">
          <el-select v-model="editForm.gradeName" multiple>
            <template v-for="v in editForm.stage">
              <el-option
                v-for="dict in dict.type['grade' + v]"
                :key="v + dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </template>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="授课班级" prop="classNames">
          <el-select v-model="editForm.classNames" multiple>
            <el-option
              v-for="dict in bjlb"
              :key="dict.id"
              :label="dict.className"
              :value="dict.className"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="临时教师" prop="temporary">
          <el-select v-model="editForm.temporary">
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="导入"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listDept } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { subjectlistselect } from "@/api/common";
import { classlist } from "@/api/jcgl/bjgl";
import {
  teacherlist,
  teacherAdd,
  teacherEdit,
  teacherDel,
  userResetPwd,
} from "@/api/jcgl/jsgl";
import { debounce } from "lodash";
export default {
  name: "Basic_jsgl",
  dicts: ["school_segment_type", "grade", "grade1", "grade2", "grade3"],
  data() {
    return {
      firstLoad: true,
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
        deptId:
          this.$route.query.deptId ||
          (this.$auth.hasRole("admin")
            ? ""
            : this.$store.state.user.deptId.toString()),
        gradeName: this.$route.query.gradeName,
        classNames: this.$route.query.classNames,
        subject: "",
        nickName: "",
        userId: "",
        userName: "",
      },
      editKmVisible: false,
      editForm: {
        nickName: "",
        userName: "",
        password: "",
        deptId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId.toString(),
        roleIds: [],
        subject: [],
        stage: [],
        gradeName: [],
        classNames: [],
        temporary: "0",
      },
      rules: {
        nickName: [
          { required: true, message: "教师姓名不能为空", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "手机号&账号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "所属学校为空", trigger: "change" },
        ],
        roleIds: [
          { required: true, message: "角色不能为空", trigger: "change" },
        ],
        subject: [
          { required: true, message: "授课科目不能为空", trigger: "change" },
        ],
        stage: [
          { required: true, message: "授课学段不能为空", trigger: "change" },
        ],
        gradeName: [
          { required: true, message: "授课年级不能为空", trigger: "change" },
        ],
        classNames: [
          { required: true, message: "授课班级不能为空", trigger: "change" },
        ],
      },
      deptList: [],
      roleList: [],
      xklb: [],
      allBjlb: [],

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/import",
      },
    };
  },
  computed: {
    bjlb: function () {
      return this.allBjlb.filter((item) => {
        return (
          this.editForm.gradeName.indexOf(item.gradeId.toString()) != -1 &&
          this.editForm.deptId == item.deptId
        );
      });
    },
    queryParamsBjlb: function () {
      return this.allBjlb.filter((item) => {
        return (
          this.queryParams.gradeName == item.gradeId &&
          item.schoolId == this.queryParams.deptId
        );
      });
    },
  },
  created() {
    this.getList();
    if (this.$auth.hasRole("admin")) {
      listDept().then((res) => {
        this.deptList = res.data.filter((item) => {
          return item.type == 1;
        });
      });
    }
    listRole({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.roleList = res.rows.filter((item) => {
        return item.roleKey != "admin";
      });
    });
    subjectlistselect("-1").then((res) => {
      this.xklb = res.data;
    });

    classlist({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.allBjlb = res.rows;
    });
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  methods: {
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),
    getList() {
      this.loading = true;
      this.tableData = [];
      teacherlist(this.queryParams)
        .then((response) => {
          response.rows = response.rows.map((item) => {
            return {
              ...item,
            };
          });
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.multiple = !selection.length;
    },

    edit(row) {
      if (row) {
        this.editForm.userId = row.userId;
        this.editForm.nickName = row.nickName;
        this.editForm.userName = row.userName;
        this.editForm.password = row.password;
        this.editForm.deptId = row.deptId;
        this.editForm.temporary = row.temporary.toString();
        if (row.subject) {
          this.editForm.subject = row.subject.split(",");
        }
        if (row.stage) {
          this.editForm.stage = row.stage.split(",");
        }
        if (row.gradeName) {
          this.editForm.gradeName = row.gradeName.split(",");
        }
        if (row.classNames) {
          this.editForm.classNames = row.classNames.split(",");
        }
        if (row.userRoleVoList) {
          this.editForm.roleIds = row.userRoleVoList.map((item) => {
            return item.roleId;
          });
        }
      }
      console.log(this.editForm,'row.stage',row.stage);
      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        nickName: "",
        userName: "",
        password: "",
        deptId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId.toString(),
        roleIds: [],
        subject: [],
        stage: [],
        gradeName: [],
        classNames: [],
        temporary: "0",
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          let data = {
            ...this.editForm,
            subject: this.editForm.subject.join(","),
            stage: this.editForm.stage.join(","),
            classNames: this.editForm.classNames.join(","),
            gradeName: this.editForm.gradeName.join(","),
          };

          if (this.editForm.userId) {
            req = teacherEdit;
            delete data.password;
          } else {
            req = teacherAdd;
          }

          if (this.$auth.hasRole("admin")) {
            data.deptName = this.deptList.filter((item) => {
              return item.deptId == data.deptId;
            })[0].deptName;
          } else {
            data.schoolName = this.$store.state.user.deptName;
          }

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    del(userId) {
      this.$modal.confirm("请确认进行删除操作").then(() => {
        teacherDel(userId ? userId : this.ids).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },
    czmm(row) {
      this.$modal.confirm("请确认进行重置密码操作").then(() => {
        userResetPwd({ userId: row.userId }).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },

    handleSearch() {
      this.debouncedSearch();
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://bs-exam-bucket.oss-cn-beijing.aliyuncs.com/dev/bsta/exam/uploadPath/upload/template/teacher_template.xlsx"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    stageChange() {
      this.editForm.gradeName = [];
      this.editForm.classNames = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 240px;
  }
}
</style>